# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'Me4886': {
        #  腾龙支付 支付宝原生大额 3.4% 10-10000 dwc
        #  腾龙支付 支付宝小额 3.3% 30,50,100,200,300 dwc
        #  腾龙支付 微信 3.5% 50 100 300 dwc
        'API_KEY': '0Pzdg8DQPFZoH0g27z6pWU8DuXMkUJ0oPbVrE7z9QAJx31R9jk0JR4d3griQybDK',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
    'M090e0': {
        #  腾龙支付 微信 3.5% 30,50,100,200 dwc
        'API_KEY': 'Icr5OOV1VVJM5Y1Avii8pUgTF4QQL4gJlNsCN7jAO60g1rv3ujj6JZPVrTuUOA0Z',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
    'M6e855': {
        #  腾龙支付  支付宝小额 3.3% 50,100 loki
        'API_KEY': 'jYXfVGgDzV6bms2MVuaHQ5MSyrwOXD8Kp6R2ILxFOxVC9ECcEzLaJtcMVA8x7PNe',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
    'Mf09a8': {
        #  腾龙支付  微信 3.5% 30,50,100,200 loki
        'API_KEY': 'mXMnwssgK0TtkyjS5Xtv4IBgEca1CeqIjmD8AwGpFkoC5GTe0yxpMzBE7l3+GJYN',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
    'Me42f6': {
        #  腾龙支付  支付宝小额 3.3% 50,100 witch
        'API_KEY': 'glSHyToXSCZ4h+ko5lliSiCzU9HJEoIfPTd90HsA8YDjrU8cI79PuFCZcQBmCu0r',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
    'M670c1': {
        #  腾龙支付  微信 3.5% 30,50,100,200 witch
        'API_KEY': 'PPtizcQ6/26lH1sVCEZMfZXiRBmuLrF0zrC5kR2isBbRp6bPxDB6PEFJvJeb/7Ix',
        'gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=create_neworder',
        'query_gateway': 'http://47.52.117.88/Handler/sdk.ashx?type=query_pay',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    s = s.upper()
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def gen_order_sign(d, key):
    s = 'app_id=' + d['app_id'] + '&mark=' + d['mark'] + '&notify_url=' + d['notify_url'] + '&order_id=' + d[
        'order_id'] + '&paytype=' + d['paytype'] + '&price=' + d['price'] + '&time=' + d['time'] + '&key=' + key
    _LOGGER.info("tenglongpay create order sign string is: %s", s)
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = 'api_id=' + d['api_id'] + '&mark=' + d['mark'] + '&msg=' + d['msg'] + '&order_id=' + d[
        'order_id'] + '&pay_time=' + d['pay_time'] + '&price=' + d['price'] + '&key=' + key
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'app_id=' + d['app_id'] + '&order_id=' + d['order_id'] + '&time=' + d['time'] + '&key=' + key
    return generate_sign(s)


def gen_query_rsp_sign(d, app_id):
    s = 'app_id=' + app_id + '&mark=' + d['mark'] + '&msg=' + d['msg'] + '&order_id=' + d[
        'order_id'] + '&pay_time=' + d['pay_time'] + '&price=' + d['price']
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tenglongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_rsp_sign(params, app_id):
    sign = params['sign']
    calculated_sign = gen_query_rsp_sign(params, app_id)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tenglongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'AlipayH5'
    elif service == 'wechat':
        return 'wechatpayH5'
    elif service == 'wechat_scan':
        return 'wechatpay'
    return 'AlipayH5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = str(info['app_id'])
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('price', '%.2f' % pay_amount),
        ('order_id', str(pay.id)),
        ('mark', 'charge'),
        ('notify_url', '{}/pay/api/{}/tenglongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('app_id', app_id),
        ('time', str(int(time.time()))),
        ('paytype', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("tenglongpay create: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['order_id'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=6, verify=False)
    _LOGGER.info("tenglong pay create rsp: %s", response.text)
    data = json.loads(response.text)['Result']
    return {'charge_info': data['payurl']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(str(request.DATA).split('=')[1])
    _LOGGER.info("tenglongpay notify data: %s, order_id is: %s", data, data['order_id'])
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('tenglongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = unicode(data['msg'])
    trade_no = str(data['api_id'])
    total_fee = float(data['price'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 凡是发送通知的订单均为交易成功的订单
    if trade_status == u'支付成功':
        _LOGGER.info('tenglongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = str(pay_order.id)
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('order_id', str(pay_order.third_id)),
        ('app_id', app_id),
        ('time', str(int(time.time()))),
    ))
    parameter_dict['sign'] = gen_query_sign(parameter_dict, api_key)
    _LOGGER.info("tenglongpay query data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers)
    _LOGGER.info("tenglongpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['Result']
        verify_query_rsp_sign(data, app_id)
        trade_status = unicode(data['msg'])
        trade_no = str(data['api_id'])
        total_fee = float(data['price'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == u'成功':
            _LOGGER.info('tenglongpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('tenglongpay data error, status_code: %s', response.status_code)
